import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (store.getters.token) {
      // 每个请求携带 token 信息
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// 成功信息,返回码为 0,1,2,3,4
const success = [0, 1, 2, 3, 4]

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  response => {
    const res = response.data
    if (!response.headers['content-type'].startsWith('application/json')) {
      if (response.headers['content-type'].startsWith('application/octet-stream')) {
        return response
      }
      return res
    }

    if (success.find(item => item + '' === res.code) !== undefined) {
      // 成功数据
      switch (res.code) {
        case '0':
          // 成功, 没有其它消息
          return res
        case '1':
          // 成功, warn
          Message({ message: res.message || '警告消息', type: 'warning', duration: 5 * 1000 })
          return res
        case '2':
          // 成功, info
          Message({ message: res.message || '信息', type: 'info', duration: 5 * 1000 })
          return res
        case '3':
        case '4':
        default:
          return res
      }
    }

    // 如果是 token 失效或过期错误码,则提示过期请重新登录
    let isWholeRequest = false;
    if (process.env.VUE_APP_BASE_API !== '/'){
      let reqUrl =  new URL(response.config.url)
      isWholeRequest = ['/needSecurity','/hasModule'].indexOf(reqUrl.pathname) !== -1;
    }else{
      isWholeRequest = ['/needSecurity','/hasModule'].indexOf(response.config.url) !== -1;
    }

    if (isWholeRequest){

      return {data: {}};
    }
    if (res.code === '4002') {
      // to re-login
      MessageBox.confirm('您的 session 已经过期,您可以取消并留在这个页面,或者重新登录', '确认重新登录', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })

      return Promise.reject(new Error(res.message || 'session 过期'))
    }

    // 禁止访问
    if (res.code === '4007') {
      Message({
        message: res.message || '您无权限访问此资源',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.message || '禁止访问'))
    }

    // 其它情况, 当出错信息
    Message({
      message: res.message || '系统异常',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(new Error(res.message || 'Error'))
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

/**
 * post 请求常用编码格式
 * @type {{urlencoded: {headers: {'Content-Type': string}}, plain: {headers: {'Content-Type': string}}, xml: {headers: {'Content-Type': string}}, json: {headers: {'Content-Type': string}}, formData: {headers: {'Content-Type': string}}, html: {headers: {'Content-Type': string}}}}
 */
export const headers = {
  formData: {
    headers: { 'Content-Type': 'multipart/form-data' }
  },
  json: {
    headers: { 'Content-Type': 'application/json' }
  },
  urlencoded: {
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  },
  plain: {
    headers: { 'Content-Type': 'text/plain' }
  },
  xml: {
    headers: { 'Content-Type': 'application/xml' }
  },
  html: {
    headers: { 'Content-Type': 'text/html' }
  }
}
